package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemUserService systemUserService;

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public CaptchaVo getCaptcha() {
        //1.生成验证码
        SpecCaptcha captcha = new SpecCaptcha(130, 48,4);
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        String value = captcha.text();
        System.out.println("验证码:"+value);
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString().replace("-","");
        System.out.println("KEY:"+key);
        //设定验证码的超时时间 60秒
        stringRedisTemplate.opsForValue().set(key,value,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        String image = captcha.toBase64();
        return new CaptchaVo(image,key);
    }

    /**
     * 实现步骤:
     *      1.根据uuid校验验证码是否过期
     *      2.校验用户输入的验证码是否正确 忽略大小写
     *      3.根据用户名查询数据库校验用户名是否存在
     *      4.将密码进行加密处理  校验是否正确
     *      5.生成token 返回给用户.
     */
    @Override
    public String login(LoginVo loginVo) {

        //1.校验是否过期
        if(!stringRedisTemplate.hasKey(loginVo.getCaptchaKey())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        //2.校验验证码是否正确
        if(!stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey()).equalsIgnoreCase(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //3.根据用户名查询用户信息
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(queryWrapper);

        //4.校验用户是否存在
        if(systemUser == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        //5.校验用户是否可用
        if(systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //6.校验密码是否正确
        String sha256 = DigestUtils.sha256Hex(loginVo.getPassword());
        if(!systemUser.getPassword().equals(sha256)){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //7.说明用户填写正常  返回token
        String token = JwtUtil.createToken(systemUser.getId());

        return token;
    }
}
